package NIO;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.SocketChannel;
import java.util.Iterator;
import java.util.Set;

public class NioTimerClient {

    public static void main(String[] args) {
        for (int i = 0 ; i < 1000 ; i++) {
            new Thread(new TimeClientHandler("127.0.0.1" , 8088) , "TimeClient").start();
        }
    }

    static class TimeClientHandler implements Runnable {

        private String host;
        private int port;
        private Selector selector;
        private SocketChannel socketChannel;
        private volatile boolean stop;

        public TimeClientHandler(String host, int port) {
            this.host = host;
            this.port = port;
            try {
                this.selector = Selector.open();
                socketChannel = SocketChannel.open();
                socketChannel.configureBlocking(false);
            } catch (IOException e) {
                e.printStackTrace();
                System.exit(1);
            }
        }

        public void stop() {
            stop = true;
        }

        @Override
        public void run() {
            try {
                doConnect();
            } catch (IOException e) {
                e.printStackTrace();
            }

            while (!stop) {
                try {
                    //Selects a set of keys whose corresponding channels are ready for I/Ooperations.
                    selector.select(1000);
                    Set<SelectionKey> selectionKeys =  selector.selectedKeys();
                    Iterator<SelectionKey> iterable = selectionKeys.iterator();
                    SelectionKey key = null;
                    while (iterable.hasNext()) {
                        key = iterable.next();
                        iterable.remove();
                        try {
                            handleInput(key);
                        }catch (Exception e) {
                            if (key != null) {
                                key.cancel();
                                if (key.channel() != null) {
                                    key.channel().close();
                                }
                            }
                        }
                    }
                }catch (Exception e) {
                    e.printStackTrace();
                }
            }

            //关闭多路复用器，注册在上面的Channel和Pipe都会关闭
            if (selector != null) {
                try {
                    selector.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

        private void handleInput(SelectionKey key) throws IOException {
            if (key.isValid()) {
                SocketChannel socketChannel = (SocketChannel) key.channel();
                if (key.isConnectable()) {
                    if (socketChannel.finishConnect()) {
                        socketChannel.register(selector , SelectionKey.OP_READ);
                        doWrite(socketChannel);
                    }else {
                        System.exit(1);
                    }
                }


                if (key.isReadable()) {
                    ByteBuffer byteBuffer = ByteBuffer.allocate(1024);
                    int readBytes = socketChannel.read(byteBuffer);
                    if (readBytes > 0) {
                        byteBuffer.flip();
                        byte[] bytes = new byte[byteBuffer.remaining()];
                        byteBuffer.get(bytes);
                        String body = new String(bytes , "utf-8");
                        System.out.println("The time is : "+body);
                    }else if(readBytes < 0) {
                        key.cancel();
                        socketChannel.close();
                    }else {

                    }
                }
            }
        }

        private void doConnect() throws IOException {
            if (socketChannel.connect(new InetSocketAddress(host , port))) {
                socketChannel.register(selector , SelectionKey.OP_READ);
                doWrite(socketChannel);
            }else {
                socketChannel.register(selector , SelectionKey.OP_CONNECT);
            }
        }

        private void doWrite(SocketChannel socketChannel) throws IOException {
            byte[] req = "QUERY TIME ORDER".getBytes();
            ByteBuffer writeBuffer = ByteBuffer.allocate(req.length);
            writeBuffer.put(req);
            writeBuffer.flip();
            socketChannel.write(writeBuffer);
            if (!writeBuffer.hasRemaining()) {
                System.out.println("send order 2 server succeed.");
            }
        }
    }
}
